﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace SP2010DevExtensions.Helper
{
    public class VsPackageHelper
    {
        public static void AddSVcTokenExtensionReplacement(DTE dte)
        {
            //var dteType = (DTE) Package.GetGlobalService(typeof (DTE));

            var globalOleServiceProvider = (IOleServiceProvider)dte;
            var globalServiceProvider = new ServiceProvider(globalOleServiceProvider);

            var sln = globalServiceProvider.GetService(typeof(SVsSolution)) as IVsSolution;


            IVsHierarchy hiearachy = null;

            if (sln != null)
                sln.GetProjectOfUniqueName(dte.Solution.Projects.Item(1).FullName, out hiearachy);

            var buildPropStorage = (IVsBuildPropertyStorage)hiearachy;

            if (buildPropStorage != null)
            {
                var svcExtensionAdded =SvcTokenReplacementAdded(buildPropStorage);
                if(!svcExtensionAdded)
                    ErrorHandler.ThrowOnFailure(buildPropStorage.SetPropertyValue("TokenReplacementFileExtensions",
                                                                              String.Empty, (uint)_PersistStorageType.PST_PROJECT_FILE, "svc"));
            }
        }

        private static bool SvcTokenReplacementAdded(IVsBuildPropertyStorage buildPropStorage)
        {
            string value;
            ErrorHandler.ThrowOnFailure(buildPropStorage.GetPropertyValue("TokenReplacementFileExtensions", string.Empty,(uint) _PersistStorageType.PST_PROJECT_FILE, out value));

            if(string.IsNullOrEmpty(value)) return false; 
            var extensinos = value.Split(new[] {';'});
            return extensinos.Contains("svc");
        }
    }
}
